# -*- coding: utf-8 -*-
"""
 ----------------------------------------
|File Name:     parse_sta
|Author:        WYT
|date:          2020/8/5
 ----------------------------------------
|  Change Activity:
|                   2020/8/5:
-----------------------------------------
"""
from lxml import etree
from util.selenium.webdriver.common.by import By

from spider_data.spiderBaseMethod import bm
from util.g import g


def parse_sta(driver=None):
    try:
        innoinfo_loc = (By.LINK_TEXT, '企业创新能力')

        bm.detail_switch_iframe(driver=driver)

        bm.wait(driver=driver, ele_loc=innoinfo_loc)

        driver.find_element(*innoinfo_loc).click()

        inno_tit_loc = (By.CSS_SELECTOR, '#title')
        bm.wait(driver=driver, ele_loc=inno_tit_loc)
        sta_loc = (By.CSS_SELECTOR, 'div.cxTab ul li:nth-of-type(2)')

        bm.click(driver=driver, ele_loc=sta_loc)
        text = driver.page_source
        tree = etree.HTML(text)

        # # # 这里分出一个函数 用来解析和存储 科技成果转化数据
        # page_objs = bm.get_page_num(driver=driver)
        # for p_index, pn in enumerate(page_objs, 1):
        IAStaDesc = list()
        i = 1
        while True:
            # if i != 1:
            #     page_objs = bm.get_page_num(driver=driver)
            #     page_objs[p_index - 1].click()

            text = driver.page_source
            tree = etree.HTML(text)
            record = tree.xpath('//tbody[@class="tableBody"]/tr')
            # # # TODO 当 data_year 有值时 不采集 科技成果转化 数据
            sta_li = parse_sta_(record=record)
            IAStaDesc.extend(sta_li)
            next_btn = bm.get_ele(driver=driver, ele_loc=g.next_btn_loc)
            onclick = None
            try:
                onclick = next_btn.get_attribute("onclick")
            except Exception as err:
                g.logger.error("get next page button\' attribute error: {}".format(err))
            if onclick is None:
                break
            else:
                bm.click(driver=driver, ele_loc=g.next_btn_loc)
                bm.wait(driver=driver, ele_loc=g.table_loc)
                i += 1
        return {"key": "IAStaDesc", "value": IAStaDesc}
    except Exception as err:
        msg = "error: {} file: {} lines: {}".format(err, err.__traceback__.tb_frame.f_globals["__file__"],
                                                    err.__traceback__.tb_lineno)
        g.logger.error(msg)
        raise Exception(msg)

def parse_sta_(record=None):
    try:
        a = list()
        for r_index, r in enumerate(record):
            sta_item = {'sta_name': '', 'sta_type': '', 'sta_source': '',
                        'trans_result': '', 'trans_date': '', 'sort_num': '', 'ipr_ids': '', 'rd_ids': '', 'ps_ids': ''}
            num = r.xpath('./td[1]/text()')
            sta_item['sort_num'] = bm.get_int(int_str=num)
            name = r.xpath('./td[2]/text()')
            sta_item['sta_name'] = bm.get_first(name)
            sta_type_name = r.xpath('./td[3]/text()')
            sta_item['sta_type'] = sta_type_name
            sta_source_name = r.xpath('./td[4]/text()')
            sta_item['sta_source'] = sta_source_name
            trans_result_name = r.xpath('./td[5]/text()')
            sta_item['trans_result'] = trans_result_name
            date = r.xpath('./td[6]/text()')
            sta_item['trans_date'] = bm.get_int(int_str=date)
            ips = r.xpath('./td[7]/text()')
            sta_item['ipr_ids'] = bm.sta_get_ids(id_str=ips)
            rds = r.xpath('./td[8]/text()')
            sta_item['rd_ids'] = bm.sta_get_ids(id_str=rds)
            ps = r.xpath('./td[9]/text()')
            sta_item['ps_ids'] = bm.sta_get_ids(id_str=ps)
            a.append(sta_item)
            # print(sta_item)

            # SaveData().save(table='ent_res_sta', value=sta_item)
        return a
    except Exception as err:
        msg = "error: {} file: {} lines: {}".format(err, err.__traceback__.tb_frame.f_globals["__file__"],
                                                    err.__traceback__.tb_lineno)
        g.logger.error(msg)
        raise Exception(msg)